package org.xiongchuan.xwifimouse.tool;

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WifiMouseServer {
	
	public ServerSocket MouseServer;
	public Robot robot;
	public int listeningPort = 17080;
	
	public WifiMouseServer() throws Exception{
		robot = new Robot();
		MouseServer = new ServerSocket(listeningPort);
		System.out.println("Wifi Mouse Server Listening at Port:"+MouseServer.getLocalPort());
		while(true){
			Socket socket = MouseServer.accept();
			System.out.println("client connected,ip:"+socket.getInetAddress()+",port:"+socket.getPort());
			DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));  
            getReqData(dis);
            dis.close();
            socket.close();
		}
	}
	
	//执行操作
	public void doAction(String str){
		if("left".equals(str)){
			System.out.println("action:向左");
			robot.keyPress(KeyEvent.VK_LEFT);
		}else if("right".equals(str)){
			System.out.println("action:向右");
			robot.keyPress(KeyEvent.VK_RIGHT);
		}else if("up".equals(str)){
			System.out.println("action:向上");
			robot.keyPress(KeyEvent.VK_UP);
		}else if("down".equals(str)){
			System.out.println("action:向下");
			robot.keyPress(KeyEvent.VK_DOWN);
		}
		else if("enter".equals(str)){
			System.out.println("action:选中");
			robot.keyPress(KeyEvent.VK_ENTER);
		}else if("esc".equals(str)){
			System.out.println("action:取消");
			robot.keyPress(KeyEvent.VK_ESCAPE);
		}else if("close".equals(str)){
			
		}
	}
	
	//读取数据
	public void getReqData(InputStream is){
		int bufferSize = 20;
		byte[] buffer = new byte[bufferSize];
		int eof;
		try {
			while((eof = is.read(buffer)) != -1){
				System.out.println("len:" + eof);
				String str = new String(buffer,Charset.forName("UTF-8"));
				System.out.println("command:"+str);
				String cmd = checkIfCmd(str);
				buffer = new byte[bufferSize];
				if(!"".equals(cmd))doAction(cmd);
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	//判断是否存在命令
	public String checkIfCmd(String str){
		Pattern pattern = Pattern.compile("\\[(up|down|left|right|enter|esc|close)\\]");
		Matcher matcher = pattern.matcher(str);
		if(matcher.find()){
			System.out.println("group(0):"+matcher.group(0));
			System.out.println("group(1):"+matcher.group(1));
			return matcher.group(1);
		}else{
			System.out.println("no matches");
		}
		return "";
	}

	
}
